package com.ilxqx.framework.security.handler;

import com.ilxqx.framework.security.util.AuthUtils;
import com.ilxqx.framework.system.util.ResponseUtils;
import com.ilxqx.framework.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问遭到拒绝的处理策略
 * @author venus
 */
@Component
@Slf4j
public class FrameworkAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * Handles an access denied failure.
     *
     * @param request               that resulted in an <code>AccessDeniedException</code>
     * @param response              so that the user agent can be advised of the failure
     * @param accessDeniedException that caused the invocation
     * @throws IOException      in the event of an IOException
     * @throws ServletException in the event of a ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.warn("用户[{}]试图以[{}]方式访问URI[{}]因没有权限而遭到拒绝", AuthUtils.getLoggedUserName(), request.getMethod(), request.getRequestURI());
        ResponseUtils.response(ResultUtils.failure("您没有权限"), request, response);
    }

}
